package com.xlh.dokka.svc.service;

import com.xlh.dokka.api.DokkaConfigService;
import com.xlh.dokka.svc.dao.DokkaConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cheer
 */
@Service
@Slf4j
public class DokkaConfigServiceImpl implements DokkaConfigService {

    @Autowired
    private DokkaConfigMapper dokkaConfigMapper;

    private ReentrantLock lock = new ReentrantLock();

    private volatile Integer containerQuotaCache;

    @Override
    public Integer getContainerQuota() {
        if (containerQuotaCache != null) {
            return containerQuotaCache;
        }
        lock.lock();
        try {
            if (containerQuotaCache != null) {
                return containerQuotaCache;
            }
            containerQuotaCache = dokkaConfigMapper.getContainerQuota();
            return containerQuotaCache;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Boolean saveContainerQuota(Integer containerQuota) {
        lock.lock();
        try {
            Long currentId = dokkaConfigMapper.getId();
            if (currentId == null) {
                dokkaConfigMapper.insert(containerQuota);
            } else {
                dokkaConfigMapper.update(currentId, containerQuota);
            }
            containerQuotaCache = containerQuota;
            return true;
        } catch (Exception e) {
            log.error("config failed", e);
        } finally {
            lock.unlock();
        }
        return false;
    }
}
